package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.api.learning.model.dto.UserDTO;
import com.xuecheng.api.teaching.model.dto.CompanyDTO;
import com.xuecheng.common.domain.code.CommonErrorCode;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.common.domain.response.RestResponse;
import com.xuecheng.common.domain.uaa.LoginUser;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.learning.convert.UserConvert;
import com.xuecheng.learning.entity.Member;
import com.xuecheng.learning.entity.User;
import com.xuecheng.learning.mapper.MemberMapper;
import com.xuecheng.learning.mapper.UserMapper;
import com.xuecheng.learning.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserMapper userMapper;
    /**
     * 远端调用查询usrDTO
     *
     * @param userName
     * @return
     */
    @Override
    public RestResponse<UserDTO> getUserByUserName(String userName) {
        if (StringUtil.isBlank(userName)){
            ExceptionCast.cast(CommonErrorCode.E_110006);
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, userName);
        User user = this.getOne(wrapper);
        UserDTO userDTO = UserConvert.INSTANCE.entity2dto(user);

        return RestResponse.success(userDTO);
    }

    @Override
    public PageVO<UserDTO> getUserListByCompanyId(PageRequestParams params, Long companyId) {
        // 1.业务传入参数的判断
        Long pageNo = params.getPageNo();
        Integer pageSize = params.getPageSize();
        // 2.构建分页查询
        if (ObjectUtils.isEmpty(pageNo) || pageNo < 1) {
            pageNo = PageRequestParams.DEFAULT_PAGE_NUM;
        }
        if (ObjectUtils.isEmpty(pageSize) || pageSize < 1) {
            pageSize = PageRequestParams.DEFAULT_PAGE_SIZE;
        }
        Page<User> page = new Page<>(pageNo, pageSize);


        if (ObjectUtils.isEmpty(companyId)){
            ExceptionCast.cast(CommonErrorCode.E_100108);
        }
        LambdaQueryWrapper<Member> memberWrapper = new LambdaQueryWrapper<>();
        memberWrapper.eq(Member::getCompanyId,companyId);
        List<Member> members = memberMapper.selectList(memberWrapper);
        List<Long> UserIdList = members.stream().map(Member::getUserId).collect(toList());

        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.in(User::getId,UserIdList);
        Page<User> userPage = this.page(page, userWrapper);
        List<User> userPageRecords = userPage.getRecords();
        if (ObjectUtils.isEmpty(userPageRecords)){
            ExceptionCast.cast(CommonErrorCode.E_100104);
        }
        List<UserDTO> userDTOS = UserConvert.INSTANCE.entitys2dtos(userPageRecords);

        PageVO<UserDTO> pageVO = new PageVO(userDTOS, page.getTotal(), pageNo, pageSize);
        return pageVO;
    }


    @Transactional
    @Override
    public UserDTO getUserByPhone(String phone, Long companyId, LoginUser loginUser) {
        //获取user（被绑定人信息）
        if (StringUtil.isBlank(phone)){
            ExceptionCast.cast(CommonErrorCode.E_110006);
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User user = this.getOne(wrapper);
        if (ObjectUtils.isEmpty(user)){
            ExceptionCast.cast(CommonErrorCode.E_100104);
        }
        UserDTO dto = UserConvert.INSTANCE.entity2dto(user);



        return dto;
    }

    @Override
    public UserDTO bingUser(String phone, Long userId, LoginUser loginUser, CompanyDTO company) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId,userId);
        User user = this.getOne(wrapper);

        //插入 member数据(member为user和company的中间表)
        Member member = new Member();
        member.setCompanyId(company.getCompanyId());
        member.setCreatePeople(loginUser.getUsername());
        member.setId(null);
        member.setUserId(user.getId());

        int insert = memberMapper.insert(member);
        if (insert<1){
            ExceptionCast.cast(CommonErrorCode.E_110015);
        }
        UserDTO dto = UserConvert.INSTANCE.entity2dto(user);
        return dto;
    }
}
